package com.base.myproject.client.HR.Training;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.Editdisable;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.grid.*;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
/**
 * 年度培训计划
 * @author Administrator
 *
 */
public class Training_YearlyTrainingPlan extends BaseJDBCPanel{
	
	
	String treeDepId = null;                       //将当前树形结构中选中的部门id保存
	String treeDepName = null;                     //将当前树形结构中选中的部门name保存
	TreePanel<TreeNodeModelData> treepanel = null;
	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>("id","name","SystemInfo","where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",true);
	Button btnAdd = null;
	Button btnDelete = null;
	StoreFilterField field = null;   
	BaseFormPanel form = null;
	Button btnApproved = null;
	String bname = null;
	String results = null;
	String bcode = Env.getEnvbcode();
	
	public Training_YearlyTrainingPlan(){
		String sql = "select substring('id like '''+replace(permissionsbcode,';','%'' or id like '''),9," +
		"len('id like '''+replace(permissionsbcode,';','%'' or id like '''))-21) as result from" +
		" busipermissions where bcode = '"+bcode+"' and busicode = 8010";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
		@Override
			public void onFailure(Throwable caught) {	
			}
			@Override
			public void onSuccess(DataSet result) {  
			   results = result.getValue(0, "result");
			   init();
			}
		});
	}
	
	public void complete(){
		super.complete();
	}
	
	public void init(){
		initWidget();
    	registerMainStore(store1);
		registerStore(store1);
		bname = Env.getEnvname();
	}
	
	public void initWidget(){
		HorizontalPanel cp = new HorizontalPanel();
		VerticalPanel vp = new VerticalPanel();		
		vp.setSpacing(2);
		HorizontalPanel s = new HorizontalPanel();
		HorizontalPanel hp = new HorizontalPanel();
		hp.setSpacing(3);
		
		
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.WEST, 200);  
		northData.setCollapsible(true);  
		northData.setFloatable(true);  
		northData.setHideCollapseTool(true);  
		northData.setSplit(true);  
		northData.setMargins(new Margins(5, 5, 0, 0));
		
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
	    centerData.setMargins(new Margins(5,0,0,0));  
	    
		s.setHeight("25");
		vp.add(this.createQuery());
		
		hp.add(this.createToolBar2());
		hp.add(this.createToolBar());
		vp.add(hp);
		
		ContentPanel center = new ContentPanel();
		center.setHeaderVisible(false);
		center.add(vp);
		
		ContentPanel panel = new ContentPanel();
		panel.setHeading("选择部门");
		panel.setCollapsible(true);
		panel.add(getTreePanel());
		add(panel,northData);
		add(center,centerData);
		
		cp.setStyleName("hp_css");//添加一个css属性
		this.layout();
	}
	
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	private TreePanel<TreeNodeModelData> getTreePanel(){
		if(treepanel == null){
			initTreePanel();
		}
		return treepanel;
	}
	
	private BaseTreeStore<TreeNodeModelData> getTreeStore(){
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}
	
	private BaseTreeStore<TreeNodeModelData> initTreeStore(){
		StoreInfo info = new StoreInfo();
		String sql2 = "select icode,id,name from SystemInfo where id like "+results+" order by id asc";
		info.setSql(sql2);
		info.setTreesortcolumn("id");
		info.setKeyname(new String[]{ "icode" });
		info.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(info,false);
		treeStore.load();
		return treeStore;
	}
	
	private void initTreePanel(){
		treepanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treepanel.setWidth(200);
		treepanel.setHeight(506);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);
		treepanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		
		treepanel.addListener(Events.OnClick,
			new Listener<TreePanelEvent<TreeNodeModelData>>() {
				public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
					if(be.getItem().getChildCount() == 0){
						String id = be.getItem().get("id").toString();
						treeDepId=id;
						treeDepName=be.getItem().get("name").toString();
						set_grid(id);
					}
				}
			});
	}
	public void set_grid(String id){
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_YearlyTrainingPlan");
		info2.setKeyname(new String[] { "icode" });
		String where=" where 1=1 and ";
		if(id.length()<5){
			where=where+" sectionCode like '" +id+ "%25'";
		}else{
			where=where+" sectionCode = '" +id+ "'";
		}
		info2.setSql("select * from hr_YearlyTrainingPlan "+where);//这里sql的linke %%  有问题
		grid2.getStore().setStoreinfo(info2);
		grid2.getStore().reload();
		grid2.getView().refresh(true);
    }
	
	private FieldSet createQuery(){
		FieldSet query = new FieldSet();
		query.setHeading("查询操作");
		
		HorizontalPanel s=new HorizontalPanel();
		s.setHeight("20");
		s.add(new Label("快速查询: "));
		cread_field();
		s.add(field);
		query.add(s);
		return query;
	}
	
	BaseStore<BusiObject> store = null;
	public BaseStore<BusiObject> getStore(){
		if(store==null) {
			createStore();
		}
		return store;
	}
	
	public BaseStore<BusiObject> createStore(){
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("micode");
		type.getField("micode").setType(Long.class);
		
		type.addField("YearMonth");
		type.getField("YearMonth").setType(Date.class);
		
		type.addField("topic");
		type.getField("topic").setType(String.class);
		
		type.addField("objectives");
		type.getField("objectives").setType(String.class);
		
		type.addField("participants");
		type.getField("participants").setType(String.class);
		
		type.addField("trainer");
		type.getField("trainer").setType(String.class);
		
		type.addField("changedTime");
		type.getField("changedTime").setType(Integer.class);
		
		type.addField("readOnly");
		type.getField("readOnly").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_YearlyTrainingPlan_list");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_YearlyTrainingPlan_list where micode = '{icode}'");
		info.setParent(getStore1());
		info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "micode"  });// 关联主表字段
		
		store = new BaseStore<BusiObject>(type, info);
		store.addEditdisableItem(new Editdisable("readOnly","1",BaseStore.EditDisableType.EQUALS));
		return store;
	}
	
	BaseStore<BusiObject> store1 = null;
	public BaseStore<BusiObject> getStore1(){
		if(store1 == null){
			createStore1();
		}
		return store1;
	}
	
	ModelType type = new ModelType();
	private BaseStore<BusiObject> createStore1(){
		
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("sectionCode");
		type.getField("sectionCode").setType(String.class);
		
		type.addField("Yearly");
		type.getField("Yearly").setType(String.class);
		
		type.addField("approvedBy");
		type.getField("approvedBy").setType(String.class);
		
		type.addField("approvedDate");
		type.getField("approvedDate").setType(Date.class);
		
		type.addField("readOnly");
		type.getField("readOnly").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_YearlyTrainingPlan");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_YearlyTrainingPlan where 1=2");
		store1 = new BaseStore<BusiObject>(type, info);
		store1.addEditdisableItem(new Editdisable("readOnly","1",BaseStore.EditDisableType.EQUALS));
		return store1;
	}
	
	ContentPanel panel = null;
	private ContentPanel createToolBar(){
		panel = new ContentPanel();
		panel.setHeaderVisible(false);
		ToolBar toolbar = new ToolBar();
		btnAdd = new Button("添加");
		btnDelete = new Button("删除");
		btnAdd.addListener(Events.OnClick, getListener());
		btnDelete.addListener(Events.OnClick, getListener());
		btnAdd.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.addrecord()));
		btnDelete.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.deleterecord())); 
		toolbar.add(btnAdd);
		toolbar.add(btnDelete);
		panel.setTopComponent(toolbar);
		panel.add(getBaseGrid());
		return panel;
	}
	
	ContentPanel panel2 = null;
	private ContentPanel createToolBar2(){
		panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		ToolBar toolbar = new ToolBar();
		btnApproved = new Button("审批");
		btnApproved.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.auction_hammer()));
		btnApproved.setWidth(60);
		btnApproved.addListener(Events.OnClick, getListener());
		toolbar.add(btnApproved);
		panel2.setTopComponent(toolbar);
		panel2.add(getGrid());
		return panel2;
	}
	
	BaseGrid grid2 = null;
	public BaseGrid getGrid() {
		if (grid2 == null) {
			createGrid2();
		}
		return grid2;
	}
	
	private void createGrid2(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		DateField dateField1 = new DateField();
		
		ColumnConfig C5 = new ColumnConfig("Yearly", "年", 50);
		TextField<String> yearly = new TextField<String>();
		yearly.setName("Yearly");
		C5.setEditor(new CellEditor(yearly));
		columns.add(C5);
		
		ColumnConfig C3 = new ColumnConfig("sectionCode", "分部门", 80);
		sectionCode.setReadOnly(true);
		sectionCode.setName("sectionCode");
		C3.setRenderer(sectionCode);
		C3.setEditor(sectionCode.getCelEditor());
		columns.add(C3);

		ColumnConfig C7 = new ColumnConfig("approvedBy", "审批人", 60);
		TextField<String> approvedBy = new TextField<String>();
		approvedBy.setName("approvedBy");
		C7.setEditor(new CellEditor(approvedBy));
		columns.add(C7);
		
		ColumnModel cm = new ColumnModel(columns);
		grid2 = new BaseGrid(getStore1(), cm){
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (treeDepId == null ) {
					MessageBox.alert("警告", "请选择一个部门后再添加新信息", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("sectionCode", treeDepId);
				grid2.getStore().add(hp);
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid2.setSelectionModel(cbs);
		grid2.setBorders(false);
		Tools.setResize(grid2,0.22,0.70);
	}
	
	BaseGrid grid = null;
	public BaseGrid getBaseGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}
	
	private void createGrid(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		DateField dateField1 = new DateField();
		
		ColumnConfig C5 = new ColumnConfig("YearMonth", "年月", 80);
	    C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM"));
		columns.add(C5);
		
		ColumnConfig C3 = new ColumnConfig("topic", "培训项目", 120);
		TextField<String> topic = new TextField<String>();
		topic.setName("topic");
		C3.setEditor(new CellEditor(topic));
		C3.setRenderer(new GridCellRenderer<ModelData>() {              
		       public String render(ModelData model, String property, ColumnData d, int rowIndex,
		          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {             
		    	  StringBuffer topic = new StringBuffer();
		    	  topic.append("<div style=\"white-space:normal; \" >");
		    	  topic.append(model.<String>get("topic"));
		    	  topic.append("</div>");
	              return topic.toString();                                                   
		      }                                                                                 
		    });
		columns.add(C3);

		
		ColumnConfig C7 = new ColumnConfig("objectives", "培训目标", 150);
		TextField<String> objectives = new TextField<String>();
		objectives.setName("objectives");
		C7.setEditor(new CellEditor(objectives));
		C7.setRenderer(new GridCellRenderer<ModelData>() {              
	       public String render(ModelData model, String property, ColumnData d, int rowIndex,
	          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {             
	    	  StringBuffer objective = new StringBuffer();
              objective.append("<div style=\"white-space:normal; \" >");
              objective.append(model.<String>get("objectives"));
              objective.append("</div>");
              return objective.toString();                                                   
	      }                                                                                 
	    });
		columns.add(C7);
		
		ColumnConfig C8 = new ColumnConfig("participants", "参训者", 80);
		TextField<String> participants = new TextField<String>();
		participants.setName("participants");
		C8.setEditor(new CellEditor(participants));
		columns.add(C8);
		
		ColumnConfig C11 = new ColumnConfig("trainer", "培训者", 80);
		TextField<String> trainer = new TextField<String>();
		trainer.setName("trainer");
		C11.setEditor(new CellEditor(trainer));
		columns.add(C11);
		
		ColumnConfig C12 = new ColumnConfig("changedTime", "更改次数", 80);
		NumberField changedTime = new NumberField();
		changedTime.setName("changedTime");
		C12.setEditor(new CellEditor(changedTime));
		C12.setHidden(true);
		columns.add(C12);
		
		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid(getStore(), cm,false,false);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setSelectionModel(cbs);
		grid.setBorders(false);
		Tools.setResize(grid,0.63,0.70);
	}
	
	protected boolean Select(Store<BusiObject> store,
			BusiObject parent, BusiObject record, String property,
			String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {

			Object name = record.get(type.getField(i).getName());
			
			//TODO
			if (name!=null&&name.toString().indexOf(filter.toLowerCase()) != -1) {
				return true;
			}
		}
	
		return false;
	}	
	
	public void cread_field(){
		field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {

			return	Select(store,parent,record,property,filter);
			}
			@Override
			protected void onFilter() {
				super.onFilter();

				// grid.getSelectionModel().select(0);
			}
		};
		field.setAutoWidth(true);
		field.setToolTip("对当前部门数据进行查找");
		field.bind(getStore1());
		this.field = field;
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	public Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                    
				try {                                                      
					if (sync == 1) {                                   
						if (be.getType() == Events.Select) { 
							
						}else if(be.getType() == Events.OnBlur){
							
						}else if(be.getType() == Events.OnClick){
							if(be.getSource().equals(btnAdd)){
								if(treeDepId == null){
									MessageBox.alert("提示", "请选择分部门！", null);
								}else if(getStore1().getValue("Yearly") == null){
									MessageBox.alert("提示", "请添加年度", null);
								}else{
									Long micode = Long.parseLong(getStore1().getValue("icode").toString());
									String year = getStore1().getValue("Yearly").toString();
									if(year == null){
										MessageBox.alert("提示", "请选择年度！", null);
									}else if(getStore().getCount() != 0){
										MessageBox.alert("提示", "对应的年度已有数据，请重新选择年度！", null);
									}else{
										for(int i = 1;i < 13;i ++){
											String y = year + "-" + i;
											BusiObject bo = new BusiObject();
											bo.set("micode", micode);
											bo.set("YearMonth", dateFormat(y));
											getStore().add(bo);
										}
									}
								}
								
							}else if(be.getSource().equals(btnDelete)){
								Long micode1 = Long.parseLong(getStore1().getValue("icode").toString());
								if(micode1 == 0){
									MessageBox.alert("提示", "请选择部门对应的年度！", null);
								}else{
									String sql = "delete from hr_YearlyTrainingPlan_list where micode = "+micode1;
									save_sql(sql);
									grid2.getStore().reload();
								}
							}else if(be.getSource().equals(btnApproved)){
								if(treeDepId == null){
									
								}else if(getStore1().getCount() == 0){
									
								}else{
									Long micode = Long.parseLong(getStore1().getValue("icode").toString());
									String sqladd = "update hr_YearlyTrainingPlan set approvedBy = '"+bname+"' where icode="+micode+"";
									grid2.getSelectionModel().getSelectedItem().set("approvedBy", bname);
									save_sql(sqladd);
									grid2.getStore().reload();
									grid2.getView().refresh(true);
									String sqlgrid = "update hr_YearlyTrainingPlan set readOnly = '1' where icode="+micode+"";
									save_sql(sqlgrid);
									String sql2 = "update hr_YearlyTrainingPlan_list set readOnly = '1' where micode="+micode+"";
									save_sql(sql2);
								}
								
							}
						} else if (be.getType() == Events.Changed){
							
						}else if (be.getType() == Events.KeyUp) { 
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent)be).getKeyCode() == 13){       // 回车                    
								}                          
							}                                  
						}                                          
					}                                                  
				} finally {                                                
					sync--;                                            
				}                                                          
			}                                                              
		};                                                               
		return defaultlistener;                                          
	}
	
	public Date dateFormat(String date){
		Date df_date = new Date();
		String[] strdates = date.split("-");
		int year = Integer.parseInt(strdates[0]);
		int month = Integer.parseInt(strdates[1]);
		df_date.setYear(year-1900);
		df_date.setMonth(month-1);
		return df_date;
	}
	
	private boolean  save_sql(String sql){
		CommandSyncsql csql = new CommandSyncsql();//执行sql命令
		String delsql =sql;
		csql.getV().add(delsql);
		if(csql.getV().size()<=0){
			return false;
		}else{
			CommandSyncContainer list = new CommandSyncContainer();//可以添加的命令
			 list.add(csql);
		
			 GreetingServiceAsync greetingService = GWT
				.create(GreetingService.class);
			 greetingService
				.SendCommandSync(
						list,
						new AsyncCallback<CommandSyncReturnObject>() {
							@Override
							public void onFailure(
									Throwable caught) {
								MessageBox.alert("错误",
										"网络连接失败", null);
							}
							@Override
							public void onSuccess(
									CommandSyncReturnObject result) {
								if (result.isB()) {
									Info.display("提示信息", "添加成功");								
								}
								else{
									MessageBox.alert("错误",
											"错误，错误代码"+result.getMessage(), null);
									
								}
							}
						});
		}
		return true;
	}	
}
